<template>
  <div class="app-container" v-loading="pageLoading">
    <el-button type="primary" class="fr" @click="createItems" v-permission="'material.add'">创建
    </el-button>
    <div class="filter-container">
      <el-cascader v-model="query.type_id" filterable style="width: 260px;" placeholder="设备类型" clearable
        class="filter-item" @keyup.enter.native="research" @clear="research" :props="MachineTypeProps"
        :options="MachineType">
      </el-cascader>
      <el-button class="filter-item" type="success" plain @click="research">查询</el-button>
      <el-button class="filter-item" type="info" plain @click="exportData" :loading="exportLoading">导出 </el-button>

    </div>
    <z-table :list="list" :tableProps="tableProps" :columns="columns" @editItem="editItemPlan" @deleteItem="deleteItem">
    </z-table>
    <z-pagination :pagination="pagination" :total="total" :page.sync="query.page" :limit.sync="query.size"
      @change="getList"></z-pagination>
    <!-- <z-form-dialog :name="name" :data="data" :formProps="formProps" :fields="fields" :submitLoading="submitLoading"
      :visible.sync="editFormVisible"></z-form-dialog> -->
    <el-dialog :title="data.id ? '编辑' : '创建'" :width="formProps.dialogWidth" :close-on-click-modal="false"
      :visible.sync="editFormVisible">
      <div style="padding-right: 100px">
        <el-form :model="data" v-bind="formProps">
          <el-row>
            <el-col :span="12">
              <el-form-item label="设备类型">
                <span slot="label">
                  <span class="text-red">*</span>
                  <span>设备类型</span>
                </span>
                <el-cascader v-model="data.type_id" filterable style="width: 100%;" clearable :props="MachineTypeProps"
                  :options="MachineType" @change="typeChange">
                </el-cascader>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="设备编号">
                <el-select v-model="data.machine_id" clearable filterable style="width: 100%">
                  <el-option v-for="o in deviceList" :key="o.value" :label="o.label" :value="o.value"> </el-option>
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="点检周期">
                <span slot="label">
                  <span class="text-red">*</span>
                  <span>点检周期</span>
                </span>
                <el-select v-model="data.period" clearable style="width: 100%" @change="setFData">
                  <el-option v-for="(item,index) in frequency" :key="index+'a'" :label="item.label" :value="item.value">
                  </el-option>

                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="点检频率">
                <span slot="label">
                  <span class="text-red">*</span>
                  <span>点检频率</span>
                </span>
                <el-input-number v-model="data.frequency" :min="1" @change="numberChange">
                </el-input-number>
              </el-form-item>
            </el-col>
          </el-row>
          <!-- 天 -->
          <el-row v-if="data.period == '日'">
            <el-form-item label="点检时间">
              <span slot="label">
                <span class="text-red">*</span>
                <span>点检时间</span>
              </span>
              <span v-for="(item,index) in data.time_json" :key="index">
                <el-time-picker v-model="item['time']" value-format="HH:mm" format='HH:mm' :picker-options="{
      selectableRange: '00:00:00 - 23:59:59',
     
      
    }" class="mb-5" placeholder="任意时间点">
                </el-time-picker>
                <br />
              </span>
            </el-form-item>
          </el-row>
          <!-- 周 -->
          <el-row v-if="data.period == '周'">
            <el-form-item label="点检时间">
              <span slot="label">
                <span class="text-red">*</span>
                <span>点检时间</span>
              </span>
              <span v-for="(item,index) in data.time_json" :key="index">
                <el-select v-model="item['week']" clearable style="width:100px">
                  <el-option v-for="(item,index) in week" :key="index +'b'" :label="item.label" :value="item.value">
                  </el-option>
                </el-select>
                {{  ' '}}
                <el-time-picker v-model="item['time']" value-format="HH:mm" format='HH:mm' :picker-options="{
      selectableRange: '00:00:00 - 23:59:59',
      
    }" class="mb-5" placeholder="任意时间点">
                </el-time-picker>
                <br />
              </span>
            </el-form-item>
          </el-row>
          <!-- 月 -->
          <el-row v-if="data.period == '月'">
            <el-form-item label="点检时间">
              <span slot="label">
                <span class="text-red">*</span>
                <span>点检时间</span>
              </span>
              <span v-for="(item,index) in data.time_json" :key="index">
                每月 <el-select v-model="item['day']" clearable style="width:100px">
                  <el-option v-for="(index) in 31" :key="index+'c'" :label="index" :value="index">
                  </el-option>

                </el-select> 日
                {{' '}}<el-time-picker v-model="item['time']" value-format="HH:mm" format='HH:mm' :picker-options="{
      selectableRange: '00:00:00 - 23:59:59',

    }" class="mb-5" placeholder="任意时间点">
                </el-time-picker>
                <br />
              </span>
            </el-form-item>
          </el-row>
          <!-- 年 -->
          <el-row v-if="data.period == '年'">
            <el-form-item label="点检时间">
              <span slot="label">
                <span class="text-red">*</span>
                <span>点检时间</span>
              </span>
              <span v-for="(item,index) in data.time_json" :key="index">
                每年<el-select v-model="item['month']" clearable style="width:100px">
                  <el-option v-for="(index) in 12" :key="index+'d'" :label="index" :value="index">
                  </el-option>

                </el-select> 月
                {{' '}}
                <el-select v-model="item['day']" clearable style="width:100px">
                  <el-option v-for="(index) in 31" :key="index+'f'" :label="index" :value="index">
                  </el-option>
                </el-select> 日
                {{' '}}<el-time-picker v-model="item['time']" value-format="HH:mm" format='HH:mm' :picker-options="{
      selectableRange: '00:00:00 - 23:59:59',
  
    }" class="mb-5" placeholder="任意时间点">
                </el-time-picker>
                <br />
              </span>
            </el-form-item>
          </el-row>
          <!-- 弹性时间 -->
          <el-row>
            <el-form-item label="弹性时间/H">
              <el-input v-model="data.flex_time"></el-input>
            </el-form-item>
            <el-row>
              <el-col :span="12">
                <el-form-item label="点检岗位"><span slot="label">
                    <span class="text-red">*</span>
                    <span>点检岗位</span>
                  </span>
                  <el-cascader style="width: 100%" v-model="data.handler_post_id" :options="userData" :props="userProps"
                    clearable>
                  </el-cascader>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="点检审核岗位">
                  <span slot="label">
                    <span class="text-red">*</span>
                    <span>点检审核岗位</span>
                  </span>
                  <el-cascader style="width: 100%" v-model="data.audit_post_id" :options="userData" :props="userProps"
                    clearable>
                  </el-cascader>
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item label="备注">
              <el-input type="textarea" v-model="data.remarks"></el-input>
            </el-form-item>
            <el-col :span="24">
              <el-form-item label="点检项">
                <span slot="label">
                  <span class="text-red">*</span>
                  <span>点检项</span>
                </span>
                <el-button type="primary" class="mb-5" @click="addspotCheck">添加</el-button>
                <el-button type="danger" class="mb-5" @click="delectspotCheck">删除</el-button>
                <br>
                <span>
                  可以多选删除
                </span>
                <z-table :list="spotCheckList" :tableProps="spotChecktableProps" :columns="spotCheckcolumns"
                  @selection-change='selectionChange'>
                  <template v-slot:content="v">
                    <span v-if="v.key == 'method'">
                      {{getMatchingData(v.row[v.key],'method')}}
                    </span>
                    <span v-else-if="v.key=='pattern'">
                      {{v.row[v.key]== 0 ? '勾选' :'填值'}}
                    </span>
                    <span v-else>{{ v.row[v.key] }}</span>
                  </template>
                </z-table>
              </el-form-item>

            </el-col>

          </el-row>
        </el-form>

        <div class="text-right">
          <el-button @click="editFormVisible = false">取消</el-button>
          <el-button type="primary" @click="submits">确定</el-button>
        </div>
      </div>
    </el-dialog>
    <!-- 添加点检项 -->
    <AddSpotCheck :addspotCheckShow="addspotCheckShow" :spotCheckIds='spotCheckIds' @addItem="addSpotItem" />
  </div>
</template>
<script>
import commonMixin from '@/views/_common/mixin'
import AddSpotCheck from '@/views/tpm/components/addSpotCheck'
import { deleteChildren } from '@/utils/index.js'
import dayjs from 'dayjs'
export default {
  name: 'checkingPlan',
  mixins: [commonMixin],
  components: { AddSpotCheck },
  props: {},
  data() {
    return {
      query: {
        type_id: '',
        page: 1,
        size: 10,
      },
      name: '点检计划',
      api: this.$api.TpmSpotCheckPlan,
      baseUrl: this.$api.baseUrl,
      MachineType: [],
      deviceList: [],
      spotCheckList: [],
      spotCheckIds: [],
      postForList: true,
      MachineTypeProps: {
        label: 'machine_type_name',
        value: 'id',
        children: 'child',
        emitPath: false,
      },
      tableProps: {
        border: true,
        opsColWith: 80,
        fixed: false,
        hideOperations: false,
      },
      frequency: [
        { label: '日', value: '日' },
        { label: '周', value: '周' },
        { label: '月', value: '月' },
        { label: '年', value: '年' },
      ],
      week: [
        { label: '周一', value: 1 },
        { label: '周二', value: 2 },
        { label: '周三', value: 3 },
        { label: '周四', value: 4 },
        { label: '周五', value: 5 },
        { label: '周六', value: 6 },
        { label: '周日', value: 7 },
      ],
      methodOptions: [],
      deleteSpotList: [],
      initData: {
        period: '日',
        frequency: 1,
        time_json: [{ ['month']: null, ['day']: null, ['week']: null, ['time']: dayjs().format('HH:mm') }],
        remarks: '',
      },
      columns: [
        { title: '设备类型', key: 'machine_type_name' },
        { title: '设备编号', key: 'machine_code' },
        // { title: '点检项', key: 'items' },
        { title: '点检周期', key: 'period' },
        { title: '点检频次', key: 'frequency' },
        // { title: '点检时间', key: 'time_json' },
        { title: '弹性时间', key: 'flex_time' },
        { title: '点检岗位', key: 'handler_post_name', width: 100 },
        { title: '点检审核岗位', key: 'audit_post_name', width: 100 },
        { title: '备注', key: 'remarks' },
        { title: '修改人', key: 'modify_user', width: 100 },
        { title: '最后修改时间', key: 'modify_time', width: 100 },
      ],

      // 人员的选择
      userProps: {
        emitPath: false,
      },
      userData: [],

      // 有点检项后点检项table
      addspotCheckShow: false,
      spotChecktableProps: {
        border: true,
        opsColWith: 80,
        fixed: false,
        hideOperations: true,
        selection: {
          showSelection: true,
        },
      },
      spotCheckcolumns: [
        { title: '设备类型', key: 'machine_type_name' },
        { title: '点检内容', key: 'content' },
        { title: '点检标准', key: 'standard' },
        { title: '点检方法', key: 'method' },
        { title: '点检形式', key: 'pattern' },
        { title: '修改人', key: 'modify_user', width: 100 },
        { title: '最后修改时间', key: 'modify_time', width: 100 },
      ],
    }
  },
  computed: {},
  watch: {},
  created() {
    this.research()
    this.getMachineType()
    this.getpositions()
    this.post()
    this.typeChange()
  },
  mounted() {},
  methods: {
    createItems() {
      this.spotCheckList = []
      this.deleteSpotList = []
      this.createItem()
    },
    // 创建点检计划提交
    submits() {
      let jsontime = JSON.stringify(this.data.time_json)
      this.data.time_json = jsontime
      let items = []
      this.spotCheckList.map((i) => {
        items.push(i.id)
      })
      let Data = {
        data: this.data,
        items: items,
      }
      this.data = Data
      let url = this.api + 'add'
      this.submitLoading = true
      this.$request(url, this.data, 'post')
        .then((r) => {
          this.$message.success('操作成功')
          this.editFormVisible = false
          this.getList()
        })
        .finally(() => {
          this.submitLoading = false
          this.spotCheckIds = []
        })
    },
    // 编辑
    editItemPlan(v) {
      this.pageLoading = true
      let url = this.api + 'getbyid'
      this.$request(url, {
        id: v.id,
      })
        .then((r) => {
          this.spotCheckList = []
          let timejson = JSON.parse(r.time_json)
          this.data = r
          this.data.time_json = timejson
          this.spotCheckList = r.item_data

          this.editFormVisible = true
        })
        .finally(() => {
          this.pageLoading = false
        })
    },

    // 获取岗位
    post() {
      let Data = {
        page: 1,
        size: 100,
      }
      this.$request(this.baseUrl + 'Tpm/TpmEquipmentPost/GetList', Data, 'post').then((r) => {
        const { list } = r
        this.userData = list.map((i) => ({
          label: i.positions_name,
          value: i.id,
        }))
      })
    },

    getMachineType() {
      this.$request(this.baseUrl + 'Tpm/MachineType/GetTreeList').then((r) => {
        this.MachineType = deleteChildren(r, 'child')
      })
    },
    typeChange(v) {
      let data = {
        machine_type_id: v,
        page: 1,
        size: 100,
      }
      this.$request(this.baseUrl + 'Tpm/Machine/GetList', data, 'post').then((r) => {
        const { list } = r
        this.deviceList = list.map((i) => ({
          label: i.machine_name,
          value: i.id,
        }))
      })
      if (!v) return
      let Data = {
        type_id: v,
        page: 1,
        size: 100,
      }
      this.$request(this.baseUrl + 'Tpm/TpmSpotCheckItem/GetList', Data, 'post').then((r) => {
        const { list } = r
        this.spotCheckList = list
      })
    },
    // 确定添加点检项
    addSpotItem(val) {
      let arr = this.spotCheckList.concat(val)
      let newArr = this.uniqueFun(arr, 'id')
      this.spotCheckList = newArr
      this.addspotCheckShow = false
    },
    uniqueFun(arr, type) {
      const res = new Map()
      return arr.filter((a) => !res.has(a[type]) && res.set(a[type], 1))
    },
    // 添加点检项
    addspotCheck() {
      this.addspotCheckShow = true
      this.spotCheckIds = []
      this.spotCheckList.forEach((i) => {
        this.spotCheckIds.push(i.id)
      })
    },
    selectionChange(val) {
      this.deleteSpotList = val
    },
    // 删除点检项
    delectspotCheck() {
      // 从数组arr中删除数组to_remove中存在的元素
      let newArr = this.spotCheckList.filter((x) => !this.deleteSpotList.some((item) => x.id === item.id))
      this.spotCheckList = newArr
      this.deleteSpotList = []
    },
    // 点检周期发生改变的时候改变f的值
    setFData() {
      this.data.frequency = 1
      this.data.time_json = [{ ['month']: null, ['day']: null, ['week']: null, ['time']: dayjs().format('HH:mm') }]
      this.numberChange()
    },
    // 点检频率发生变化的时候触发
    numberChange() {
      if (this.data.time_json.length > this.data.frequency) {
        let array = this.data.time_json.slice(0, this.data.frequency)
        this.data.time_json = array
      } else {
        if (this.data.period == '日') {
          for (let i = this.data.time_json.length; i < this.data.frequency; i++) {
            let tmp = { ['month']: null, ['day']: null, ['week']: null, ['time']: dayjs().format('HH:mm') }
            this.data.time_json.push(tmp)
          }
        } else if (this.data.period == '周') {
          for (let i = this.data.time_json.length; i < this.data.frequency; i++) {
            let tmp = { ['month']: null, ['day']: null, ['week']: 1, ['time']: dayjs().format('HH:mm') }
            this.data.time_json.push(tmp)
          }
        } else if (this.data.period == '月') {
          for (let i = this.data.time_json.length; i < this.data.frequency; i++) {
            let tmp = { ['month']: null, ['day']: 1, ['week']: null, ['time']: dayjs().format('HH:mm') }
            this.data.time_json.push(tmp)
          }
        } else if (this.data.period == '年') {
          for (let i = this.data.time_json.length; i < this.data.frequency; i++) {
            let tmp = { ['month']: 1, ['day']: 1, ['week']: null, ['time']: dayjs().format('HH:mm') }
            this.data.time_json.push(tmp)
          }
        }
      }
      let tmp = this.frequency.find((i) => i.value == this.data.period)
      this.data.remarks = `每${tmp.label}点检${this.data.frequency}次`
    },
    // 获取匹配数据
    getMatchingData(val, code) {
      if (code == 'method') {
        let tmp = this.methodOptions.find((i) => i.value == val)
        return tmp ? tmp.label : ''
      }
    },
    // 获取点检方法
    getpositions() {
      this.$request(this.$api.dictionary + 'getdirectchildren', {
        parentType: 'spotcheckMethod',
      }).then((r) => {
        this.methodOptions = r.map((i) => ({
          label: i.label,
          value: i.value * 1,
        }))
      })
    },
  },
}
</script>

<style lang="scss" scoped></style>